/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package action;

import dao.CategoryDAO;
import dao.ProductDAO;
import dao.mysql.CategoryDAOImpl;
import dao.mysql.ProductDAOImpl;
import javax.servlet.http.HttpServletRequest;
import model.Category;
import model.Product;
import utility.DBConnection;

/**
 *
 * @author Student
 */
public class ProductSaveAction implements Action {

    @Override
    public String execute(HttpServletRequest request) {
        String url = "";
        DBConnection db = new DBConnection();
        ProductDAO dao = new ProductDAOImpl(db.getConnection());
        CategoryDAO cDao = new CategoryDAOImpl(db.getConnection());
        try{
            String name = request.getParameter("name");
            String description = request.getParameter("description");
            double price = Double.valueOf(request.getParameter("price"));
            Category cat = 
                    cDao.getCategoryById(Integer.valueOf(request.getParameter("category")));
            
            Product product = new Product();
            product.setName(name);
            product.setDescription(description);
            product.setPrice(price);
            product.setCategory(cat);
            
            dao.save(product);
            
            url = "controller?action=product_list";
        }catch(Exception ex){
            request.setAttribute("message", ex.getMessage());
            url = "errors.jsp";
        }
        return url;
    }
}
